
//
// 120407 - AH - (Midtun) Created.
//

package org.soekrat.engine.util;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * <p>
 *   Utility methods of use when working with parameters represented by single
 *   string.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
public final class ParameterStringParser 
{
  // Utility pattern dictates private constructor.
  private ParameterStringParser(){} 
  
  /**
   * <p>
   *   Parse a string giving parameters in the format 
   *   "name1=val1,name2=val2,...".
   * </p>
   * <p>
   *   Simply ignores what can not be parsed.
   * </p>
   * @param s String to parse, {@code null} is treated as the empty string: a
   *          empty map.          
   * @return Map where keys are the parsed parameter names and values are parsed
   *         parameter values.
   */
  public static Map<String, String> parseParameterString(String s)
  {
    s=(s==null) ? "" : s.trim();
    
    Map<String, String> retVal=new HashMap<String, String>();
    
    StringTokenizer st=new StringTokenizer(s, ",");
    while (st.hasMoreTokens())
    {
      String curr=st.nextToken();
      int idx=curr.indexOf('=');
      if (idx!=-1)
      {
        String name=curr.substring(0, idx).trim();
        if (name.length()>0)
        {
          String value=curr.substring(idx+1).trim();
          if (value.length()>0)
          {
            retVal.put(name, value);
          }
        }
      }
    }
    
    return retVal;
  }
  
}
